package etnorservice.etnor_service.filter;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: cc
 * @Date: 2024/08/22/12:34
 **/
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class AdminTokenFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {

        String requestURI = request.getRequestURI();

        // 检查请求是否以/admin开头
        if (requestURI.startsWith("/admin")) {
            // 获取请求头中的token
            String token = request.getHeader("Authorization");

            // 判断token是否存在
            if (token == null || token.isEmpty()) {
                // 如果token不存在，则返回401 Unauthorized状态码
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                response.getWriter().write("Unauthorized: Token is missing or invalid.");
                return;
            }

            // 这里可以添加验证token的逻辑
            // ...

            // 如果token有效，继续执行后续的过滤器链
            filterChain.doFilter(request, response);
        } else {
            // 对于非/admin开头的请求，直接放行
            filterChain.doFilter(request, response);
        }
    }
}
